package com.couldsail.takeaway.controller.user;

import com.couldsail.takeaway.common.result.Result;
import com.couldsail.takeaway.constant.JwtClaimsConstant;
import com.couldsail.takeaway.pojo.dto.UserLoginDTO;
import com.couldsail.takeaway.pojo.dto.UserUpdateDTO;
import com.couldsail.takeaway.pojo.entity.User;
import com.couldsail.takeaway.pojo.vo.UserLoginVO;
import com.couldsail.takeaway.pojo.vo.UserVO;
import com.couldsail.takeaway.properties.JwtProperties;
import com.couldsail.takeaway.service.UserService;
import com.couldsail.takeaway.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Update;
import org.springframework.web.bind.annotation.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@CrossOrigin(origins = "*") // 允许所有来源的请求跨域
@RequestMapping("/user")
@Api(tags = "用户相关接口")
@RequiredArgsConstructor
public class UserController {
    private final UserService userService;
    private final JwtProperties jwtProperties;
    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("微信登录")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) throws IOException, CloneNotSupportedException {
        log.info("微信登录:{}",userLoginDTO);
        User user = userService.wxLogin(userLoginDTO);
        //为微信用户生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String jwt = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        UserLoginVO build = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(jwt).build();
        return Result.success(build);
    }
    @GetMapping("/detail")
    @ApiOperation("用户信息")
    public Result<UserVO> detail(){
        log.info("获取用户个人信息");
        return Result.success(userService.getDetail());
    }
    @PostMapping("/update")
    @ApiOperation("修改个人信息")
    public Result<String> update(@RequestBody UserUpdateDTO userUpdateDTO){
        log.info("个人信息已更新{}",userUpdateDTO);
        userService.updateDetail(userUpdateDTO);
        return Result.success("个人信息已更新");
    }
}
